#include "boxthread.h"

#include "QtCore"
#include "QtNetwork"

#include "nam.h"
#include "nbr.h"

BoxThread::BoxThread(int socketDescriptor, BoxServer *a_box_server, QObject *parent)
: QThread(parent), m_socketDescriptor(socketDescriptor)
{
	qDebug("BoxThread::BoxThread(%d)", m_socketDescriptor);
}

BoxThread::~BoxThread()
{
	qDebug("BoxThread::~BoxThread(%d)", m_socketDescriptor);
}

void BoxThread::run()
{
	handleIncomingConnection(m_socketDescriptor);
	return;
}

void BoxThread::handleIncomingConnection(int socketDescriptor)
{
	qDebug("BoxServer::handleIncomingConnection(): %d \n", socketDescriptor);
	QTcpSocket v_front_socket;
	v_front_socket.setSocketDescriptor(socketDescriptor);
#if 0x0
	v_front_socket.waitForReadyRead(1000);
#else
	while(!v_front_socket.waitForReadyRead(1))
	{
		qDebug() << "single step" << QDateTime::currentDateTime();

		QCoreApplication::processEvents();
	}
#endif
	QByteArray v_raw_request = v_front_socket.readAll();
	qDebug() << "[v_raw_request]" << v_raw_request;

	QBuffer v_dev(&v_raw_request);
	v_dev.open(QIODevice::ReadOnly);
	v_dev.seek(0);
	QByteArray v_line = v_dev.readLine();
	qDebug() << "[v_line]" << v_line;
	v_line.replace("\r", "");
	v_line.replace("\n", "");
	QList<QByteArray> v_split = v_line.split((char)32);
	qDebug() << "[v_split[0]]" << v_split[0];
	Q_ASSERT(v_split[0] == "GET" || v_split[0] == "POST");
	QByteArray v_encoded_url = v_split[1];

	QUrl v_url;
	v_url.setEncodedUrl(v_encoded_url);

	QNetworkRequest v_request;
	v_request.setUrl(v_url);

	while(v_dev.canReadLine())
	{
		v_line = v_dev.readLine();
		v_line.replace("\r", "");
		v_line.replace("\n", "");
		if (v_line.length()==0) break;
		QString v_line_str = QString::fromLatin1(v_line);
		QRegExp v_rx("^([^:]+):(.*)$");
		int v_pos = v_rx.indexIn(v_line_str);
		qDebug() << "[v_pos]" << v_pos;
		if(v_pos == -1) continue;
		QString v_f_nam = v_rx.cap(1);
		QString v_f_val = v_rx.cap(2).trimmed();
		qDebug() << v_f_nam << v_f_val;
		if(v_f_nam == "Connection") continue;
		if(v_f_nam == "Accept-Encoding") continue;
		qDebug() << "[set]";
		v_request.setRawHeader(v_f_nam.toLatin1(), v_f_val.toLatin1());
	}

	QNetworkAccessManager back_nam;
	QNetworkReply *v_reply = back_nam.get(v_request);

	QByteArray v_response;
	NetworkBatchRequest v_nbr(v_reply, &v_response, false);
	//v_nbr.wait();
	v_nbr.waitWithType(NetworkBatchRequest::ReadyRead);

	QNetworkReply::NetworkError v_error = v_reply->error();
	if(v_error != QNetworkReply::NoError)
	{
		qDebug() << "[v_error]" << v_error;
		v_front_socket.write("HTTP/1.1 504 Gateway Time-out\r\n");
		v_front_socket.write("\r\n");
		v_reply->deleteLater();
		v_front_socket.disconnectFromHost();
		v_front_socket.waitForDisconnected();
		return;
	}
#if 0x0
	QByteArray v_response = back_nam.doGet(v_url);
#endif
	qDebug() << "[QNetworkRequest::HttpStatusCodeAttribute]" << v_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	qDebug() << "[QNetworkRequest::HttpReasonPhraseAttribute]" << v_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute);

	QString v_attr_http_status = v_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
	QString v_attr_http_reason =  v_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
	QString v_http_status_line = QString("HTTP/1.1 %1 %2\r\n").arg(v_attr_http_status).arg(v_attr_http_reason);
	qDebug() << v_http_status_line;

	//v_front_socket.write("HTTP/1.1 200 OK\r\n");
	v_front_socket.write(v_http_status_line.toLatin1());

	QList<QByteArray> headerList = v_reply->rawHeaderList();
	foreach(QByteArray ba, headerList)
	{
		QByteArray headerData = v_reply->rawHeader(ba);
		qDebug() << "ba+headerData=" << ba << headerData;
		if(ba == "Content-Encoding")
		{
			qDebug() << "skip ba";
			continue;
		}
		if(ba == "Transfer-Encoding")
		{
			qDebug() << "found: Transfer-Encoding";
			if(headerData == "chunked")
			{
				qDebug() << "skip chunked";
				continue;
			}
		}
		v_front_socket.write(ba);
		v_front_socket.write(": ");
		v_front_socket.write(headerData);
		v_front_socket.write("\r\n");
	}

	v_front_socket.write("\r\n");

	qDebug() << v_response.size();
	qDebug() << v_response;

#if 0x0
	v_front_socket.write(v_response);
#else
	while(v_nbr.waitWithType(NetworkBatchRequest::ReadyRead))
	{
		QByteArray v_read = v_nbr.read(80);
		v_front_socket.write(v_read);
	}
#endif

	v_reply->deleteLater();
	v_front_socket.disconnectFromHost();
	v_front_socket.waitForDisconnected();
}

